package com.app.mp3player.service;

import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Queue;

import android.app.Service;
import android.content.Intent;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Environment;
import android.os.Handler;
import android.os.IBinder;
import android.util.Log;

import com.app.mp3player.lrc.LrcProcessor;
import com.app.mp3player.model.Mp3Info;
import com.app.utils.AppConstant;

public class PlayService extends Service {
	private static final String TAG = "PlayService";
	
	private boolean isPlaying = false;
	private boolean isPause = false;
	private boolean isReleased = false;
	
	private MediaPlayer mediaPlayer;
	
	ArrayList<Object> queues = null;
	private Handler handler = new Handler();
	private long begin = 0;
	private long currentTimeMill = 0;
	private long nextTimeMill = 0;
	private long pauseTimeMill = 0;
	
	private Mp3Info mp3Info;
	
	private UpdateTimeCallBack updateTimeCallBack;
	private String message = null;
	
	public PlayService() {
	}

	@Override
	public IBinder onBind(Intent intent) {
		throw new UnsupportedOperationException("Not yet implemented");
	}

	@Override
	public int onStartCommand(Intent intent, int flags, int startId) {
		mp3Info = (Mp3Info)intent.getSerializableExtra("mp3Info");
		int Msg = intent.getIntExtra("Msg", 0);
		if(mp3Info!=null){
			if(Msg == AppConstant.PLAY_ACTION.PLAY){
				Log.i(TAG, "onStartCommand------->start play");
				play(mp3Info);
			}else{
				if(Msg == AppConstant.PLAY_ACTION.PAUSE){
					pause();
				}
			}
		}
		return super.onStartCommand(intent, flags, startId);
	}
	
	/**
	 * 暂停
	 */
	public void pause() {
		if(isPlaying){
			mediaPlayer.pause();
			handler.removeCallbacks(updateTimeCallBack);
			pauseTimeMill = System.currentTimeMillis();
			isPause = true;
		}else{
			mediaPlayer.start();
			//再次播放
			handler.postDelayed(updateTimeCallBack, 5);
			//得到再次开始播放的时间
			begin = System.currentTimeMillis() - pauseTimeMill + begin;
		}
		isPlaying = isPlaying?false:true;
	}

	/**
	 * 播放音乐
	 * @param info
	 */
	public void play(Mp3Info info){
		String path = getMp3Path(info);
		
		Log.i(TAG, "play------------->"+path);
		
		//创建音乐播放器
		mediaPlayer = MediaPlayer.create(this, Uri.parse("file://"+path));
		mediaPlayer.setLooping(false);
		mediaPlayer.start();
		
		//解析歌词
		prepareLrc(info.getLrcName());
		info.getDuration();
		//设置参数
		begin = System.currentTimeMillis();
		handler.postDelayed(updateTimeCallBack, 5);
		isPlaying = true;
		isReleased = false;
	}
	
	/**
	 * 获取MP3全路劲
	 * @param info
	 * @return
	 */
	public String getMp3Path(Mp3Info info){
		String SDCardRoot = Environment.getExternalStorageDirectory()
				.getAbsolutePath();
		String path = SDCardRoot + File.separator + "mp3" + File.separator
				+ mp3Info.getMp3Name()+".mp3";
		return path;
	}
	
	/**
	 * 
	 * @param lrcName
	 */
	public void prepareLrc(String lrcName){
		try{
			
			InputStream inputStream = new FileInputStream(Environment.getExternalStorageDirectory().getAbsoluteFile()
					+ File.separator + "mp3/" + mp3Info.getLrcName());
			LrcProcessor lrcProcessor = new LrcProcessor();
			queues = lrcProcessor.process(inputStream);
			updateTimeCallBack = new UpdateTimeCallBack(queues);
			begin = 0;
			currentTimeMill = 0;
			nextTimeMill = 0;
		}catch(Exception e){
			e.printStackTrace();
		}
	}
	
	/**
	 * 更新时间
	 * @author Administrator
	 *
	 */
	class UpdateTimeCallBack implements Runnable{

		Queue times = null;
		List<String> messages = null;
		
		int line = 0;
		
		public UpdateTimeCallBack(List<Object> queues) {
			this.times = (Queue)queues.get(0);
			this.messages = (List<String>)queues.get(1);
		}



		@Override
		public void run() {
			//计算偏移量
			long offset = System.currentTimeMillis()-begin;
			
			if(currentTimeMill == 0){
				nextTimeMill = (Long)times.poll();
			}
			
			if(offset >= nextTimeMill){
				Intent intent = new Intent();
				intent.setAction(AppConstant.LRC_MESSAGE_ACTION);
				intent.putExtra("line", line);
				intent.putExtra("currentTime", offset);
				sendBroadcast(intent);
				nextTimeMill = (Long)times.poll();
				line ++;
			}
			currentTimeMill = currentTimeMill + 10;
			handler.postDelayed(updateTimeCallBack, 10);
		}
		
	}
}
